package com.laker.admin.module.excel.application.impl;

import com.laker.admin.module.excel.application.DataSourceApplication;
import com.laker.admin.module.excel.domain.DataSource;
import com.laker.admin.module.excel.repository.DataSourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;


/**
 * @author : nihongxin
 * @date : 2021/3/22
 */
@Component
public class DataSourceApplicationImpl implements DataSourceApplication {

    @Autowired
    private DataSourceRepository dataSourceRepository;

    @Override
    public DataSource save(DataSource dataSource) {
        return dataSourceRepository.save(dataSource);
    }

    @Override
    public Page<DataSource> listDataSourcePage(String keyword, Integer pageNo, Integer pageSize) {
        PageRequest page = PageRequest.of(pageNo - 1, pageSize);
        return dataSourceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate conjunction = criteriaBuilder.conjunction();
            if (!StringUtils.isEmpty(keyword)) {
                conjunction.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("dataSourceName"), "%" + keyword + "%")));
            }
            return conjunction;
        }, page);
    }

    @Override
    public DataSource getById(Long id) {
        return dataSourceRepository.getOne(id);
    }

    @Override
    public void deleteById(Long id) {
        dataSourceRepository.deleteById(id);
    }
}
